import unittest
import os
import tempfile
import sys
import os

# 添加src目录到Python路径
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'src'))

from wc import TextCounter

class TestTextCounter(unittest.TestCase):
    
    def setUp(self):
        self.test_text = "Hello world! This is a test. How are you?"
    
    def create_test_file(self, content):
        """创建临时测试文件"""
        fd, path = tempfile.mkstemp(suffix='.txt')
        try:
            with os.fdopen(fd, 'w') as f:
                f.write(content)
            return path
        except:
            os.close(fd)
            raise
    
    def test_count_chars(self):
        """测试字符统计"""
        path = self.create_test_file("hello")
        counter = TextCounter(path)
        counter.read_file()
        self.assertEqual(counter.count_chars(), 5)
        os.unlink(path)
    
    def test_count_words(self):
        """测试单词统计"""
        path = self.create_test_file("hello world test")
        counter = TextCounter(path)
        counter.read_file()
        self.assertEqual(counter.count_words(), 3)
        os.unlink(path)
    
    def test_count_sentences(self):
        """测试句子统计"""
        path = self.create_test_file("First sentence. Second sentence! Third sentence?")
        counter = TextCounter(path)
        counter.read_file()
        self.assertEqual(counter.count_sentences(), 3)
        os.unlink(path)
    
    def test_code_analysis(self):
        """测试代码分析"""
        code_content = '''# This is a comment
def hello():
    print("Hello world")
    
    return True

# Another comment
'''
        path = self.create_test_file(code_content)
        counter = TextCounter(path)
        counter.read_file()
        stats = counter.code_analysis()
        self.assertEqual(stats['total_lines'], 7)
        self.assertEqual(stats['code_lines'], 3)
        self.assertEqual(stats['blank_lines'], 2)
        self.assertEqual(stats['comment_lines'], 2)
        os.unlink(path)
    
    def test_file_not_found(self):
        """测试文件不存在的情况"""
        counter = TextCounter("nonexistent_file.txt")
        result = counter.read_file()
        self.assertFalse(result)

if __name__ == '__main__':
    unittest.main()